package com.wj.dubbo.service.welfareshop.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.wj.console.bean.welfareshop.param.ProductQuery;
import com.wj.console.bean.welfareshop.result.ProductDetail;
import com.wj.console.common.Page;
import com.wj.dubbo.service.welfareshop.entity.Product;
import com.wj.dubbo.service.welfareshop.service.ProductRepository;
import com.wj.dubbo.service.welfareshop.service.ProductService;


@Service
public class ProductServiceImpl implements ProductService{

    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    
    
    public boolean isExistsIndex(){
    	return elasticsearchTemplate.indexExists(Product.class);
    }
    
    public void createIndex(){
    	elasticsearchTemplate.createIndex(Product.class);
    }
     
    /**
     * 保存
     */
    @Override
    public void save(List<Product> products){
         productRepository.save(products);
    }
    
    /**
     * 删除
     */
    @Override
	public void delete(List<Product> products) {
		productRepository.delete(products);
	}

    @Override
	public List<Product> findAllProduct() {
		Iterable<Product> orders = productRepository.findAll();
		List<Product>productList = new ArrayList<Product>();
		Iterator iter = orders.iterator();
		while(iter.hasNext()){
			Product product = (Product)iter.next();
			productList.add(product);
		}
		return productList;
	}

    /**
     * 根据主键查询
     * @param id
     * @return
     */
    public Product findOneById(String id){
        return productRepository.findById(id);
    }
    
    /**
     * 保存/更新
     * @param product
     */
	public void save(Product product) {
		productRepository.save(product);
	}

	
	/**
	 * 产品全局搜索分页查询
	 * @param page
	 * @return
	 */
	public Page<ProductQuery, ProductDetail> queryEsSearchProductByPage(Page<ProductQuery, ProductDetail> page){
		ProductQuery query = page.getQuery();
		SearchRequestBuilder srb = elasticsearchTemplate.getClient().prepareSearch("es_welfareshop");//索引
		srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);//搜索类型
		srb.setTypes("product");//类型
//		srb.setMinScore(0.5f);
		srb.setQuery(QueryBuilders.multiMatchQuery(query.getKeyword(),"name","brand").type("most_fields").tieBreaker(0.3f));//匹配多个字段 
		if (StringUtils.isEmpty(query.getSortCreateTime())&&StringUtils.isEmpty(query.getSortRetailPrice())) {
			srb.addSort("createTime", SortOrder.DESC);
		}else{
			if(StringUtils.isEquals(query.getSortCreateTime(),"1")){
				srb.addSort("createTime", SortOrder.ASC);
			}else if(StringUtils.isEquals(query.getSortCreateTime(),"2")){
				srb.addSort("createTime", SortOrder.DESC);
			}
			
			if (StringUtils.isEquals(query.getSortRetailPrice(),"1")) {
				srb.addSort("retailPrice", SortOrder.ASC);
			}else if (StringUtils.isEquals(query.getSortRetailPrice(),"2")){
				srb.addSort("retailPrice", SortOrder.DESC);
			}
		}
		srb.setFrom(page.getCurrentPage()  * page.getPageSize()).setSize(page.getPageSize());
		SearchResponse response = srb.execute().actionGet();
		SearchHits hits = response.getHits();
		page.setTotalNum((int)hits.getTotalHits());
		List<ProductDetail> list = new ArrayList<ProductDetail>();
		for (SearchHit searchHit : hits) {
			Map<String, Object> source = searchHit.getSource();
			ProductDetail entity =  JSONObject.parseObject(JSONObject.toJSONString(source), ProductDetail.class);
			list.add(entity);
		}
		page.setItemList(list);
		return page;
	}
	
	
	/**
	 * 按类型查询产品
	 * 分页查询 
	 * 按发布时间和价格排序
	 * @param page
	 * @return
	 */
	public Page<ProductQuery, ProductDetail> queryEsSearchProductByPageSort(Page<ProductQuery, ProductDetail> page){
		ProductQuery query = page.getQuery();
		SearchRequestBuilder srb = elasticsearchTemplate.getClient().prepareSearch("es_welfareshop");//索引
		srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);//搜索类型
		srb.setTypes("product");//类型
		srb.setQuery(QueryBuilders.termQuery("rootCate", query.getRootCate()));
		if (StringUtils.isEmpty(query.getSortCreateTime())&&StringUtils.isEmpty(query.getSortRetailPrice())) {
			srb.addSort("createTime", SortOrder.DESC);
		}else{
			if(StringUtils.isEquals(query.getSortCreateTime(),"1")){
				srb.addSort("createTime", SortOrder.ASC);
			}else if(StringUtils.isEquals(query.getSortCreateTime(),"2")){
				srb.addSort("createTime", SortOrder.DESC);
			}
			
			if (StringUtils.isEquals(query.getSortRetailPrice(),"1")) {
				srb.addSort("retailPrice", SortOrder.ASC);
			}else if (StringUtils.isEquals(query.getSortRetailPrice(),"2")){
				srb.addSort("retailPrice", SortOrder.DESC);
			}
		}
		srb.setFrom(page.getCurrentPage() * page.getPageSize()).setSize(page.getPageSize());
		SearchResponse response = srb.execute().actionGet();
		SearchHits hits = response.getHits();
		page.setTotalNum((int)hits.getTotalHits());
		List<ProductDetail> list = new ArrayList<ProductDetail>();
		for (SearchHit searchHit : hits) {
			Map<String, Object> source = searchHit.getSource();
			ProductDetail entity =  JSONObject.parseObject(JSONObject.toJSONString(source), ProductDetail.class);
			list.add(entity);
		}
		page.setItemList(list);
		return page;
	}
	
}
